package com.malty.apisdk.client;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malty.apisdk.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口的客户端
 *
 * @author malty
 */
@Slf4j
public class ApiClient {

    private static final String GATEWAY_HOST = "http://localhost";

    private String accessKey;

    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String repeatRobot(String param) {
        String url = UrlBuilder
                .of(GATEWAY_HOST + "/api/mock")
                .addQuery("param", param).build();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("param", param);
        paramMap.put("timestamp", System.currentTimeMillis() / 1000 + "");
        paramMap.put("nonce", RandomUtil.randomNumbers(4));
        HttpRequest request = HttpUtil.createGet(url);
        String sign = SignUtil.genQuerySign(paramMap, secretKey);

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("timestamp", System.currentTimeMillis() / 1000 + "");
        headerMap.put("nonce", (String) paramMap.get("nonce"));
        headerMap.put("access-key", accessKey);
        headerMap.put("sign", sign);
        request.addHeaders(headerMap);

        HttpResponse response = request.execute();

        JSONObject result = JSON.parseObject(response.body());

        log.info("api invoke, path:{},param:{},result:{}", "/api/mock", "param=" + param, result);
        return result.getString("result");
    }


}
